<?php

/**
 * Class BController
 *
 * @property string $pageTitle
 *
 * @author Hua Yang <htmlcook@gmail>
 * @since 1.0
 */
class BController extends CController
{
	/**
	 * @var string
	 */
	public $layout = 'backend.views.layouts.main';

	/**
	 * @var string
	 */
	public $baseUrl;

	/**
	 * @var array 面包屑
	 */
	public $breadcrumbs = array();

	/**
	 * @var array 餐单
	 */
	public $menu = array();

	/**
	 * @var string 餐单父级当前路由
	 */
	public $menuRoute;

	public function init()
	{
		parent::init();
		$this->baseUrl = Yii::app()->getAssetManager()->publish(dirname(__FILE__) . '/../assets/backend');
	}

	/**
	 * 请求过滤
	 *
	 * @see CController::filters()
	 */
	public function filters()
	{
		return array(
			'accessControl',
			array(
				'bootstrap.filters.BootstrapFilter',
			),
		);
	}

	/**
	 * 访问规则
	 *
	 * @see CController::accessRules()
	 */
	public function accessRules()
	{
		$rules = array(
			array(
				'allow',
				'expression' => array($this, 'authorize'),
				'users' => array('@'),
			),
			array(
				'deny',
				'users' => array('*')
			)
		);
		if ($this->id == 'site') {
			array_unshift($rules, array(
				'allow',
				'actions' => array('login', 'logout', 'resetPassword', 'lostPassword', 'captcha'),
				'users' => array('*'),
			));
		}
		return $rules;
	}

	/**
	 * @param CWebUser $user
	 * @return bool
	 */
	public function authorize($user)
	{
		if ($user->getId() == User::ROOT_ID) {
			return true;
		}

		$route = $this->getRoute();
		$parts = explode('/', $route);
		do {
			if ($user->checkAccess($route, $_REQUEST)) {
				return true;
			}
			array_pop($parts);
			$route = implode('/', $parts);
		} while ($parts);
		return false;
	}

	/**
	 * 检查权限
	 *
	 * @param $route
	 * @param array $params
	 * @return bool
	 */
	public function checkAccess($route, $params = array())
	{
		$user = Yii::app()->getUser();
		if ($user->getId() == User::ROOT_ID) {
			return true;
		}

		return $user->checkAccess($route, $params);
	}

	/**
	 * 访问拒绝
	 *
	 * @throws CHttpException
	 */
	public function accessDenied()
	{
		$user = Yii::app()->getUser();
		if($user->getIsGuest()) {
			$user->loginRequired();
		} else {
			throw new CHttpException(403, Yii::t('yii','You are not authorized to perform this action.'));
		}
	}
}